package com.example.android.BluetoothChat;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class PacketData {

	private Date date;
	int powerListIndex = 0;
	static int powerListSize = 10;
	static int dataSize = 4;
	static String endBits = "@";
	static String inputDateFormat = "yyyyMMddHHmmss";
	static String outputDateFormat = "yyyy-MM-dd HH:mm:ss";
	Power[] powerList = new Power[powerListSize];
	String packet;
	SimpleDateFormat sdf;
	StringBuilder sb = new StringBuilder();
	String result = "Success";

	// Data packet example:
	// 20130321215033@DFAC@DFAC@EF09@DF77@CF36@DFAC@DFAC@EF09@DF77@CF36@DFAC@DFAC@EF09@DF77@CF36@
	public PacketData(String packet) {
		super();
		this.packet = packet;
		String[] dataPacket = packet.split(endBits);
		try {
			sdf = new SimpleDateFormat(inputDateFormat);
			date = sdf.parse(dataPacket[0]);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			result = "ParseException";
		}
		stringToData(dataPacket);
	}

	private void stringToData(String[] dataPacket) {
		// TODO Auto-generated method stub
		for (int i = 0; i < dataPacket.length; i++) {
			if (dataPacket[i].length() == dataSize) {
				Power power = new Power();
				date = addOneSecond(date);
				sdf = new SimpleDateFormat(outputDateFormat);
				String dateString = sdf.format(date);
				power.setDatatime(dateString);
				String powerData = LookupTable.lookup(dataPacket[i]);
				power.setPower(powerData);
				powerList[powerListIndex] = power;
				powerListIndex++;
			} else {
				result = "Data " + i + " is invalid";
				break;
			}
		}
	}

	public static Date addOneSecond(Date date) {
		// TODO Auto-generated method stub
		Calendar cal = Calendar.getInstance(); // creates calendar
		cal.setTime(date); // sets calendar time/date
		cal.add(Calendar.SECOND, 1); // add one second
		return cal.getTime(); // returns new date object
	}
	public static Date minusOneSecond(Date date) {
		// TODO Auto-generated method stub
		Calendar cal = Calendar.getInstance(); // creates calendar
		cal.setTime(date); // sets calendar time/date
		cal.add(Calendar.SECOND, -1); // minus one second
		return cal.getTime(); // returns new date object
	}

	public String getResult() {
		return result;
	}

	public Power[] getPowerList() {
		return powerList;
	}

	public void setPowerList(Power[] powerList) {
		this.powerList = powerList;
	}
	public static Date addNSecond(Date date, int value) {
		// TODO Auto-generated method stub
		Calendar cal = Calendar.getInstance(); // creates calendar
		cal.setTime(date); // sets calendar time/date
		cal.add(Calendar.SECOND, value); // minus one second
		return cal.getTime(); // returns new date object
	}
}
